package com.kwin.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CookieApp1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd=HH:mm:ss");
        resp.setContentType("text/html;charset=UTF-8");
        Cookie[] cookies = req.getCookies();
        String cookieValue = null;
        for (int i = 0;cookies != null && i < cookies.length; i++) {
            resp.getWriter().write("你上次登陆的时间是:");
            cookieValue = cookies[i].getValue();
            resp.getWriter().write(cookieValue);

            cookies[i].setValue(simpleDateFormat.format(new Date()));
            resp.addCookie(cookies[i]);

            break;
        }
        if (cookieValue == null) {
            Cookie cookie = new Cookie("time", simpleDateFormat.format(new Date()));
            cookie.setMaxAge(2000);
            resp.addCookie(cookie);
            resp.getWriter().write("你是第一次登陆啊");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
